<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/10/20 10:48
 * Desc: 商城
 */
class Service_Api_Malls extends Contract_Api_Product
{
    public function search(array $params = array()): array
    {
        /**
         * @var $pagesize
         * @var $page
         * @var $classify_id
         * @var $sort_id
         * @var $attr_id
         * @var $keyword
         * @var $mid
         * @var $price_id
         */
        extract($params);

        $type_id = Model_Api_V2_Malls::TYPE_ID;
        $builder = DB::select(
            'a.id', 'a.title', 'a.price', 'a.litpic', 'a.shownum', 'a.satisfyscore',
            'a.sellpoint', 'a.bookcount', 'a.iconlist', 'a.attrid', 'sell_num'
        )
            ->from(array('malls', "a"))
            ->join('member_order_statistic', 'left')
            ->on('member_order_statistic.product_id', '=', DB::expr('`sline_a`.id'))
            ->on('member_order_statistic.type_id', '=', $type_id)
            ->join('allorderlist', 'left')
            ->on('a.id', '=', DB::expr('`sline_allorderlist`.aid'))
            ->on('a.webid', '=', DB::expr('`sline_allorderlist`.webid'))
            ->on('allorderlist.typeid', '=', $type_id)
            ->where('a.ishidden', '=', 0);
        //关键词
        if (!empty($keyword)) {
            $builder->and_where('a.title', 'like', '%' . $keyword . '%');
        }
        //按属性
        if (!empty($attr_id)) {
            $attr_where = Product::get_attr_where($attr_id);
            if ($attr_where) {
                $attr_where = str_replace('a.attrid', 'sline_a.attrid', $attr_where);
                $builder->and_where(DB::expr($attr_where));
            }
        }
        //价格区间
        if (!empty($price_id)) {
            $price_arr = DB::select()
                ->from('malls_pricelist')
                ->where('id', '=', $price_id)
                ->execute()
                ->current();
            if (!empty($price_arr)) {
                $builder->and_where(DB::expr(" AND sline_a.price BETWEEN {$price_arr['lowerprice']} AND {$price_arr['highprice']}"));
            }
        }
        //按分类
        if (!empty($classify_id)) {
            $classify_where = Model_Api_V2_Malls::get_classify_where($classify_id);
            if ($classify_where) {
                $classify_where = str_replace('a.classify', 'sline_a.classify', $classify_where);
                $builder->and_where(DB::expr($classify_where));
            }
        }

        $total = $builder->execute()->count();

        //排序
        $order_by = "";
        if (!empty($sort_id)) {
            switch ($sort_id) {
                case 1:
                    $order_by = " sline_a.price ASC,";
                    break;
                case 2:
                    $order_by = " sline_a.price DESC,";
                    break;
                case 3:
                    $order_by = " sell_num DESC,";
                    break;
                case 4:
                    $order_by = " sline_a.shownum DESC,";
                    break;
            }
        }

        $order_by .= "IFNULL(`sline_allorderlist`.displayorder,9999) ASC";

        $pagesize = !empty($pagesize) ? $pagesize : 10;
        $page     = !empty($page) ? $page : 1;
        $offset   = St_Page::offset($page, $pagesize);

        $list = $builder->order_by(DB::expr($order_by))
            ->offset($offset)
            ->limit($pagesize)
            ->execute()
            ->as_array();
        if (!empty($list)) {
            // 获取营销策略
            $marketing_strategy = Model_Api_V2_Marketing_Strategy::get_instance($type_id, array('mid'=> $mid));

            foreach ($list as &$v) {
                $v['commentnum'] = Model_Comment::get_comment_num($v['id'], $type_id); //评论次数
                $v['score']      = $v['satisfyscore'] . '%';
                $v['price']      = Model_Api_V2_Malls::get_minprice($v['id'], $v);//最低价
                $v['attrlist']   = Model_Api_V2_Malls::get_attr_list($v['attrid'], $type_id);//属性列表.
                $v['iconlist']   = $this->icons($v['iconlist']);
                if (Model_Supplier::display_is_open() && $v['supplierlist']) {
                    $v['suppliername'] = Arr::get(Model_Supplier::get_supplier_info($v['supplierlist'], array('suppliername')), 'suppliername');
                }
                $v['litpic'] = $this->img_url($v['litpic'], 170, 170);
                // 营销策略
                $v['marketing_strategy'] = $marketing_strategy->get_support_application($v['id']);
            }
        }

        return array(
            'total' => $total,
            'list' => $list,
            'is_finished' => count($list) < $pagesize //是否还有更多的数据
        );
    }

    public function info(array $params = array()): array
    {
        $params['userid'] = $params['mid'];
        $data             = Model_Api_V2_Malls::detail($params);
        if (empty($data)) {
            throw new Exception('商品不存在');
        }
        foreach ($data['suit_info'] as &$suit) {
            $min_price        = 0;
            $express_template = DB::select()
                ->from('express_template')
                ->where('id', '=', $suit['freightid'])
                ->execute()
                ->current();
            if (!empty($express_template)) {
                $express_template['plan_list'] = Model_Express_Plan::get_template_planlist($suit['freightid']);
                foreach ($express_template['plan_list'] as $plan) {
                    $min_price = $min_price == 0 || ($min_price > $plan['start_price'] && $plan['start_price'] > 0) ? $plan['start_price'] : $min_price;
                }
            }

            $express_template['min_price'] = Currency_Tool::price($min_price);
            $suit['express_template']      = $express_template;
        }
        return $data;
    }

    public function query_condition(): array
    {
        $data = array(
            'sorts' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格由低到高'),
                array('id' => 2, 'name' => '价格由高到低'),
                array('id' => 3, 'name' => '销量优先'),
                array('id' => 4, 'name' => '人气推荐')
            ),
            'price' => array('name' => '价格', 'child' => array()),
        );

        //属性
        $data['attrs'] = Model_Api_V2_Malls::get_attributes();
        //价格
        $data['price']['child'] =Model_Api_V2_Malls::price_filter();
        return $data;
    }

    public function create_order(array $params = array()): array
    {
        $type_id         = Model_Api_V2_Malls::TYPE_ID;
        $mid             = $params['mid'];
        $member_info     = $params['member_info'];
        $car_id          = $params['car_id'];
        $linkman         = $params['linkman'];
        $linktel         = $params['linktel'];
        $linkemail       = Arr::get($params, 'linkemail', '');
        $remark          = Arr::get($params, 'remark', '');
        $address_id      = Arr::get($params, 'address_id', '');
        $need_kuaidi     = Arr::get($params, 'need_kuaidi', '');
        $member_card_id  = Arr::get($params, 'member_card_id', '');
        $card_tourist_id = Arr::get($params, 'card_tourist_id', '');
        $source          = Arr::get($params, 'source', 3);

        if ($need_kuaidi == 1 && !Model_Member_Address::check_address_id($mid, $address_id)) {
            throw new Exception('收货地址有误请重新选择');
        }

        $car_id_arr = explode(',', $car_id);
        $car_num    = DB::select()
            ->from('malls_cars')
            ->where('id', 'in', $car_id_arr)
            ->where('mid', '=', $mid)
            ->execute()
            ->count();
        if ($car_num < 1) {
            throw new Exception('请先添加购物车');
        }
        if ($car_num != count($car_id_arr)) {
            throw new Exception('购物车中有商品已下架');
        }

        // 获取运费
        $express_total_price = 0;
        $express_param       = array(
            'car_id' => $car_id,
            'addressid' => $address_id,
            'userid' => $mid
        );
        if ($need_kuaidi == 1) {
            $express_fee = Model_Api_V2_Malls::get_express_fee($express_param);
            if (!$express_fee['status']) {
                throw new Exception('所选收货地址不在配送范围，请重新选择');
            }
            $express_total_price = $express_fee['price'];
        }

        $auto_close_time = 0;
        $title           = "";
        $litpic          = "";

        // 循环检查
        $suits = DB::select()
            ->from('malls_cars')
            ->where('id', 'in', $car_id_arr)
            ->where('mid', '=', $mid)
            ->execute()
            ->as_array();

        $child_order = array();
        $totalPrice  = 0;//总费用
        //默认可退
        $refund_restriction = 0;
        //设置主产品的信息
        $productautoid = 0;
        $productaid    = 0;
        foreach ($suits as $v) {
            $suit = DB::select()->from('malls_suit')
                ->where("id", '=', $v['suit_id'])
                ->execute()->current();
            if (empty($suit)) {
                throw new Exception('套餐不存在');
            }

            $suit['price'] = Currency_Tool::price($suit['price']);

            if (!Model_Api_V2_Malls::check_storage($v['num'], $v['suit_id'])) {
                throw new Exception('库存不足');
            }
            $product_info = DB::select()->from('malls')->where("id", '=', $suit['productid'])->execute()->current();
            $title        = $title ?: $product_info['title'];

            $auto_close_time = $auto_close_time == 0 ? $suit['auto_close_time'] : ($auto_close_time < $suit['auto_close_time'] ? $auto_close_time : $suit['auto_close_time']);
            $productname     = $product_info['title'];
            $litpic          = $litpic ?: $suit['litpic'];
            $child           = array(
                'webid' => 0,
                'typeid' => $type_id,
                'productautoid' => $product_info['id'],
                'productaid' => $product_info['aid'],
                'productname' => $productname,
                'litpic' => $suit['litpic'],
                'price' => $suit['price'],
                'childprice' => 0,
                'jifentprice' => 0,
                'jifenbook' => $product_info['jifenbook_id'],
                'jifencomment' => 0,
                'jifenbook_id' => $product_info['jifenbook_id'],
                'paytype' => 1,
                'dingjin' => '',
                'usedate' => '',
                'departdate' => '',
                'addtime' => time(),
                'memberid' => $mid,
                'dingnum' => $v['num'],
                'childnum' => 0,
                'oldprice' => 0,
                'oldnum' => 0,
                'suitid' => $v['suit_id'],
                'status' => 1,
                'source' => $source,//来源
                'suit_name' => $suit['suitname']
            );
            $child_order[]   = $child;
            $totalPrice      += $child['price'] * $child['dingnum'];
            //如果有一个产品设置成不可退,整个订单都不能退.
            if ($suit['refund_restriction'] == 1) {
                $refund_restriction = 1;
            }
            if (!$productautoid) {
                $productautoid = $product_info['id'];
            }
            if (!$productaid) {
                $productaid = $product_info['aid'];
            }
        }

        $p_num = count($suits);
        $title = $title . "等" . $p_num . '件商品';
        if ($auto_close_time) {
            $auto_close_time = $auto_close_time + time();
        }

        $ordersn = Product::get_ordersn($type_id);

        //优惠券处理
        $coupon_id = Arr::get($params, 'coupon_id', '');
        if ($coupon_id) {
            $cid = DB::select('cid')->from('member_coupon')->where("id={$coupon_id}")->execute()->current();
            if (!$cid) {
                throw new Exception('优惠券不存在');
            }
            $coupon_discount_price = 0;
            $coupon_check          = Model_Api_V2_Malls::check_coupon($coupon_id, $totalPrice, $coupon_discount_price);
            if (!$coupon_check) {
                throw new Exception('优惠券不满足使用条件');
            }
        }

        $receiver_address_info = Db::select('province', 'city', 'area', 'receiver', 'phone', 'postcode', 'address')
            ->from('member_address')
            ->where('id', '=', $address_id)
            ->execute()
            ->current();
        $receiver_address_info = json_encode($receiver_address_info, JSON_UNESCAPED_UNICODE);

        $order = array(
            'ordersn' => $ordersn,
            'webid' => 0,
            'typeid' => $type_id,
            'productautoid' => $productautoid,
            'productaid' => $productaid,
            'productname' => $title,
            'litpic' => $litpic,
            'price' => 0,
            'childprice' => 0,
            'jifentprice' => 0,
            'jifenbook' => 0,
            'jifencomment' => 0,
            'paytype' => 1,
            'dingjin' => '',
            'usedate' => '',
            'departdate' => '',
            'addtime' => time(),
            'memberid' => $mid,
            'dingnum' => 1,
            'childnum' => 0,
            'oldprice' => 0,
            'oldnum' => 0,
            'linkman' => $linkman,
            'linktel' => $linktel,
            'linkemail' => $linkemail,
            'haschild' => 1,
            'suitid' => 0,
            'remark' => $remark,
            'status' => 1,
            'source' => $source,//来源,
            'usejifen' => 0,
            'needjifen' => 0,
            'receiver_address_id' => $address_id,
            'receiver_address_infos' => $receiver_address_info,
            'express_total_price' => $member_card_id ? 0 : $express_total_price,
            'auto_close_time' => $auto_close_time,
            'refund_restriction' => $refund_restriction

        );

        $jifen          = Arr::get($params, 'jifen', 0);
        $jifentprice_id = Model_Sysconfig::get_configs(0, 'cfg_jifen_deduction', true);
        if ($jifen) {
            //积分折扣
            $jifentprice = Model_Jifen_Price::calculate_jifentprice($jifentprice_id, $type_id, $jifen, $member_info);
            $useJifen    = empty($jifentprice) ? 0 : 1;
            $needJifen   = empty($jifentprice) ? 0 : $jifen;
            if ($useJifen == 1 && isset($jifentprice)) {
                $order['jifentprice'] = $jifentprice;
                $order['usejifen']    = 1;
                $order['needjifen']   = $needJifen;
            }
        }

        /*附加信息*/
        $extend_params = array(
            'member_card_id' => $member_card_id,
            'card_tourist_id' => $card_tourist_id,
        );

        //添加主订单
        $res = Model_Api_V2_Order::add_order($order, 'Model_Malls');

        if (!empty($coupon_check) && !empty($cid)) {
            $coupon_discount_price = !empty($coupon_discount_price) ? $coupon_discount_price : 0;
            // 使用优惠券
            DB::insert('member_order_coupon', array('cid', 'ordersn', 'cmoney', 'roleid'))->values(array($cid, $ordersn, $coupon_discount_price, $coupon_id))->execute();
            DB::update('member_coupon')->set(array('usetime' => time(), 'usenum' => 1))->where('id', '=', $coupon_id)->execute();
        }

        if (!$res || !$res['status']) {
            throw new Exception($res['msg']);
        }

        $orderInfo = Model_Member_Order::order_info($ordersn);
        $main_price = 0;
        foreach ($child_order as $vv) {
            $child_ordersn = Product::get_ordersn($type_id);
            // 添加子订单
            $child_arr            = $vv;
            $child_arr['ordersn'] = $child_ordersn;
            $child_arr['pid']     = $orderInfo['id'];
            $main_price+=$vv['price']*$vv['dingnum'];
            $res                  = Model_Api_V2_Order::add_order($child_arr, 'Model_Malls', $extend_params);
            if (!$res['status']) {
                Model_Member_Order::order_delete($orderInfo['id']);
                throw new Exception($res['msg']);
            }
        }

        DB::update('member_order')->set(['price'=>$main_price+$express_total_price])->where('ordersn', '=', $ordersn)->execute();

        //添加红包抵扣
        $envelope_member_id = Arr::get($params, 'envelope_member_id', '');
        if ($envelope_member_id) {
            if (St_Functions::is_normal_app_install('red_envelope')) {
                $envelope_member = DB::select('id', 'money')
                    ->from('envelope_member')
                    ->where("find_in_set(21,typeids)")
                    ->and_where('id', '=', $envelope_member_id)
                    ->and_where('memberid', '=', $mid)
                    ->and_where('use', '=', 0)
                    ->execute()
                    ->current();
                if ($envelope_member) {
                    //红包抵扣金额
                    $use_money = min($totalPrice, $envelope_member['money']);
                    if ($use_money > 0) {
                        $data = array('use' => 1, 'usetime' => time(), 'ordersn' => $ordersn, 'use_money' => $use_money);
                        //红包使用
                        DB::update('envelope_member')->set($data)->where('id', '=', $envelope_member_id)->execute();
                    }
                }
            }
        }

        //订单结算信息表数据更新
        Model_Member_Order_Compute::update($orderInfo['ordersn']);

        // 事件
        Hook::trigger('order_created', $order);

        // 删除购物车
        DB::delete('malls_cars')->where('mid', "=", $mid)->and_where('id', 'in', DB::expr("({$car_id})"))->execute();

        return array(
            'id' => $orderInfo['id'],
            'typeid' => $type_id,
            'ordersn' => $ordersn,
            'status' => $orderInfo['status']
        );
    }

    use Trait_Api_Malls;
}